package ulric.server;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import ulric.kit.SystemKit;

import java.io.File;

class JettyServer implements IServer {

    private static final Log LOG = LogFactory.getLog(JettyServer.class);

    private String webAppDir;
    private int port;
    private String context;
    private boolean running = false;
    private Server server;
    private WebAppContext webApp;

    JettyServer(String webAppDir, int port, String context) {
        if (StringUtils.isBlank(webAppDir))
            throw new IllegalStateException("Invalid webAppDir of web server: " + webAppDir);

        if (!new File(webAppDir).exists()) {
            throw new IllegalStateException("webAppDir[" + webAppDir + "] is nonexistent");
        }

        if (port < 0 || port > 65536)
            throw new IllegalArgumentException("Invalid port of web server: " + port);

        if (StringUtils.isBlank(context))
            throw new IllegalStateException("Invalid context of web server: " + context);

        this.webAppDir = webAppDir;
        this.port = port;
        this.context = context;
    }

    public boolean start() {
        if (!running) {
            try {
                doStart();
            } catch (Exception e) {
                LOG.error("jetty start fail", e);
                return false;
            }
            running = true;
        }
        return true;
    }

    public void stop() {
        if (running) {
            try {
                server.stop();
            } catch (Exception e) {
                LOG.error("jetty stop fail", e);
            }
            running = false;
        }
    }

    private void doStart() {
        if (SystemKit.portInUse(port)) {
            throw new IllegalStateException("port[" + port + "] is in use");
        }
        server = new Server();
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(port);
        server.addConnector(connector);

        webApp = new WebAppContext();
        webApp.setContextPath(context);
        webApp.setResourceBase(webAppDir);
        webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
        webApp.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");    // webApp.setInitParams(Collections.singletonMap("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"));

        server.setHandler(webApp);

        try {
            LOG.info("Jetty start on port: " + port);
            server.start();
            LOG.info("Jetty is started");
            // server.join();
        } catch (Exception e) {
            LOG.error("jetty start fail", e);
            System.exit(1);
        }
    }

}






